#include "baseudp.h"
#include <QThread>
#include <QDateTime>
#include "config/constants.h"
#include <QDebug>

BaseUdp::BaseUdp(QObject *parent)
{
    initConnect();
}

BaseUdp::~BaseUdp()
{

}

void BaseUdp::onSetting()
{

}

void BaseUdp::onConnect(QString ip, int port)
{
    _ip = QHostAddress(ip);
    _port = port;
    LOG_INFO << "Tcp thread id = " << QThread::currentThread();
//    this->bind(QHostAddress(ip), port);
//    connectToHost(ip, port);
//    waitForConnected();
}

void BaseUdp::onSend(QString command)
{
    LOG_INFO << "tcp send thread id = " << QThread::currentThread();
    this->writeDatagram(command.toStdString().c_str(), command.size(), _ip, _port);
}

void BaseUdp::onDisconnect()
{
    this->close();
}

void BaseUdp::onConnected()
{

}

void BaseUdp::onDisconnectd()
{

}

void BaseUdp::onRead()
{
    QByteArray array;// = readAll();
    array.resize(this->bytesAvailable());//根据可读数据来设置空间大小
    this->readDatagram(array.data(),array.size()); //读取数据

    QString res = QString::fromStdString(array.toStdString());


    //LOG_INFO <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz") << " size = " << array.size();
    emit emitData(array);
    LOG_INFO << res.toStdString();

}

void BaseUdp::onError(QAbstractSocket::SocketError e)
{

}

void BaseUdp::onStateChange(QAbstractSocket::SocketState e)
{
    emit netStateSignals(e);
}

void BaseUdp::initConnect()
{
    connect(this, SIGNAL(readyRead()), this, SLOT(onRead()));
    connect(this, SIGNAL(disconnected()), this, SLOT(onDisconnectd()));
    connect(this, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
            this,
            SLOT(onError(QAbstractSocket::SocketError)));
    connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,
            SLOT(onStateChange(QAbstractSocket::SocketState)));
}
